package com.fufufu.mail.ware.service.impl;

import com.fufufu.common.constant.WareConstant;
import com.fufufu.mail.ware.entity.PurchaseDetailEntity;
import com.fufufu.mail.ware.service.PurchaseDetailService;
import com.fufufu.mail.ware.service.WareSkuService;
import com.fufufu.mail.ware.vo.DoneVo;
import com.fufufu.mail.ware.vo.DoneVoItem;
import com.fufufu.mail.ware.vo.PurchaseMergeVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fufufu.common.utils.PageUtils;
import com.fufufu.common.utils.Query;

import com.fufufu.mail.ware.dao.PurchaseDao;
import com.fufufu.mail.ware.entity.PurchaseEntity;
import com.fufufu.mail.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePurchase(@RequestParam Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().in("status", WareConstant.purchaseEnum.CREATED.getCode(),
                        WareConstant.purchaseEnum.ASSIGNED.getCode()));
        return new PageUtils(page);
    }

    /**
     * 合并采购需求，如果指定了哪个采购单就合并过去，如果没有就创建新的采购单
     */
    @Transactional
    @Override
    public void merge(PurchaseMergeVo purchaseMergeVo) {
        Long purchaseId = purchaseMergeVo.getPurchaseId();
        List<Long> needMerge = purchaseMergeVo.getItems();
        if (needMerge == null || needMerge.size() == 0) {
            return;
        }
        // buweinull表示要新建一个采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setPriority(1);
            // 0表示新键的采购单
            purchaseEntity.setStatus(WareConstant.purchaseEnum.CREATED.getCode());
            purchaseEntity.setAmount(new BigDecimal("0"));
            Date date = new Date();
            purchaseEntity.setCreateTime(date);
            purchaseEntity.setUpdateTime(date);
            // 插入新采购单，并获得其id
            this.baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        // 查出所以待合并的detail
        List<PurchaseDetailEntity> purchaseDetailEntities1 = purchaseDetailService.listByIds(needMerge);
        // 过滤掉无法分配的detail
        purchaseDetailEntities1 = purchaseDetailEntities1.stream().filter((detail) -> detail.getStatus() == WareConstant.purchaseDetailEnum.CREATED.getCode()
                || detail.getStatus() == WareConstant.purchaseDetailEnum.ASSIGNED.getCode())
                .map((detail) -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setId(detail.getId());
                    purchaseDetailEntity.setStatus(WareConstant.purchaseDetailEnum.ASSIGNED.getCode());
                    return purchaseDetailEntity;
                })
                .collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities1);
    }


    /**
     * 采购人员接收采购单的逻辑
     * @param purchaseId
     */
    @Transactional
    @Override
    public void receive(List<Long> purchaseId) {
        if (purchaseId == null || purchaseId.size() == 0) {
            return;
        }
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        // 先获取传入id对应的采购单实体
        List<PurchaseEntity> purchaseEntities = this.baseMapper.selectBatchIds(purchaseId);
        purchaseId.clear();
        // 进行过滤，如果采购单状态不是已分配就剔除，
        purchaseEntities = purchaseEntities.stream().filter((p) -> {
            return p.getStatus() == WareConstant.purchaseEnum.ASSIGNED.getCode();
        }).peek((p) -> {
            p.setUpdateTime(new Date());
            p.setStatus(WareConstant.purchaseEnum.RECEIVED.getCode());
            purchaseId.add(p.getId());
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);
        // 通过采购单对应的采购细节的状态变成正在采购
        purchaseDetailService.updateBatchBypurchaseId(purchaseId);

    }

    @Transactional
    @Override
    public void done(DoneVo doneVo) {
        List<DoneVoItem> items = doneVo.getItems();
        // 改变采购项状态，返回值的表示是不是有订单项没有采购成功
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        boolean allFinish = purchaseDetailService.doneDetail(items, purchaseDetailEntities);
        // 改变采购单状态,只有所有的采购项都完成了采购单才是完成，否则是异常
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        Long purchaseId = doneVo.getId();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(allFinish ? WareConstant.purchaseEnum.COMPETED.getCode() : WareConstant.purchaseEnum.ERROR.getCode());
        this.updateById(purchaseEntity);
        // 采购成功的入库
        wareSkuService.saveBypurchaseDetais(purchaseDetailEntities);
    }
}